<?php
use Facebook\FacebookSession;
use Facebook\FacebookRequestException;
use Facebook\FacebookRequest;
require ('facebook/php-sdk-v4/autoload.php');
require 'cloudiary/Cloudinary.php';
require 'cloudiary/Uploader.php';
require 'cloudiary/Api.php';
/**
 *
 * @author Thanhpv
 *         @date Wed 03/09/2014
 *         file upload processing
 *         http://www.sitepoint.com/file-uploads-with-php/
 *         flashdata Codeigniter
 *         http://www.tech-faq.com/display-messages-using-flashdata-in-codeigniter.html
 *         to use session class, enable encrypt key in config.php file
 *         $config['encryption_key']='ABCDABCDABCDABCDABCDABCDABCDABCD';
 */
class ImageUpload extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		$this->load->helper ( "url" );
		// load session libarary
		$this->load->library ( 'session' );
		\Cloudinary::config ( array (
				"cloud_name" => $this->config->item ( 'cloud_name' ),
				"api_key" => $this->config->item ( 'api_key' ),
				"api_secret" => $this->config->item ( 'api_secret' ) 
		) );
	}
	public function index() {
		session_start ();
		// get Accesstoken and userId here
		if (isset ( $_REQUEST ["code"] )) {
			$appId = $this->config->item ( 'AppId' );
			$appSecret = $this->config->item ( 'AppSecret' );
			
			$code = $_REQUEST ["code"];
			$redirectURL = $this->config->item ( 'RedirectURL' );
			$access_token_details = "";
			
			// Session
			FacebookSession::setDefaultApplication ( $appId, $appSecret );
			// If you're making app-level requests:
			$session = FacebookSession::newAppSession ();
			
			if (empty ( $code )) {
				redirect ( $redirectURL );
			} else {
				$access_token_details = $this->getAccessTokenDetails ( $appId, $appSecret, $redirectURL, $code );
				if ($access_token_details == null) {
					redirect ( $redirectURL );
				}
				$_SESSION ['access_token'] = $access_token_details ['access_token'];
				// create session
				$session = new FacebookSession ( $_SESSION ['access_token'] );
				$access_token = $access_token_details ['access_token'];
				$_SESSION ["publish_permission"] = $this->getGrantedPermission ( $session );
				$user = ( array ) $this->getUserDetails ( $access_token );
				$friendList = $this->getFriendList ( $session );
				$friendLists = $this->getFriendLists ( $session );
				$privacyValue = $this->getPrivacyValue($session);
				//
				$_SESSION["privacyValue"] = $privacyValue;
				
				
				$_SESSION ["userId"] = $user ['id'];
				$_SESSION ["userName"] = $user ['name'];
				$picture = "https://graph.facebook.com/me/picture?access_token=" . $access_token;
				$_SESSION ["profilePicture"] = $picture;
				// create folder for 1st login
				$folderName = $_SESSION ["userId"];
				$destination = './UserUploads/' . $folderName;
				$mode = 0777;
				if (! is_dir ( $destination )) {
					mkdir ( $destination, $mode );
					copy ( "./UserUploads/default.jpg", $destination . "/default.jpg" );
					copy ( "./UserUploads/fb-login.jpg", $destination . "/fb-login.jpg" );
					copy ( "./UserUploads/defaultBackground.jpeg", $destination . "/defaultBackground.jpeg" );
				}
				// Save to UserDetails table and UserFriends
				$this->load->Model ( "muser" );
				if (! $this->muser->checkExist ( $_SESSION ["userId"] )) {
					$this->muser->saveUserDetails ( $_SESSION ["userId"], json_encode ( $user ), $picture );
					$this->muser->saveUserFriends ( $_SESSION ["userId"], $friendList );
					$this->muser->saveUserFriendLists ( $_SESSION ["userId"], $friendLists );
				}
				
				// unset $_SESSION["imageName"] to create folder for facebook user login
				// and use default image for user
				if (isset ( $_SESSION ["imageName"] ))
					unset ( $_SESSION ["imageName"] );
				if (isset ( $_SESSION ["isWatermarked"] ))
					unset ( $_SESSION ["isWatermarked"] );
				if (isset ( $_SESSION ["isTwoImages"] ))
					unset ( $_SESSION ["isTwoImages"] );
				if (isset ( $_SESSION ["isFramed"] ))
					unset ( $_SESSION ["isFramed"] );
				if (isset ( $_SESSION ["isFunnyEffect"] ))
					unset ( $_SESSION ["isFunnyEffect"] );
				if (isset ( $_SESSION ["backgroundImageName"] ))
					unset ( $_SESSION ["backgroundImageName"] );
				if (isset ( $_SESSION ["backgroundChanged"] ))
					unset ( $_SESSION ["backgroundChanged"] );
			}
		}
		// echo "outer";
		if (! isset ( $_SESSION ["userId"] )) {
			$_SESSION ["userId"] = $GLOBALS ["webId"];
			$_SESSION ["userName"] = "Anonymous";
		}
		$this->load->view ( "ImageUpload/index" );
	}
	public function process() {
		// cloudiary
		$cloudName = $this->config->item ( 'cloud_name' );
		$cloudApiKey = $this->config->item ( 'api_key' );
		$cloudApiSecret = $this->config->item ( 'api_secret' );
		if (isset ( $_POST )) {
			session_start ();
			// check error
			if ($_FILES ['imageUpload'] ['error'] > 0) {
				$this->session->set_flashdata ( "Error", "This image contains error" );
				redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
				return;
			}
			// check extension jpeg, jpg, png
			$fType = $_FILES ['imageUpload'] ['type'];
			$allowedExtensions = array (
					"image/jpeg",
					"image/jpg" 
			);
			$extensionError = ! in_array ( $fType, $allowedExtensions );
			// check extension
			if ($extensionError) {
				$this->session->set_flashdata ( "Error", "This image extension is incorrect" );
				redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
				return;
			}
			// check size
			$fSize = $_FILES ['imageUpload'] ['size'] / 1024 / 1024;
			if ($fSize > 2) {
				$this->session->set_flashdata ( "Error", "This image is too large" );
				redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
				return;
			}
			
			// save to specific folder on server
			// Generate specific folder
			$folderName = $_SESSION ["userId"];
			$destination = 'UserUploads/' . $folderName;
			
			// upload to cloud
			$typeOnly = str_replace ( "image/", "", $_FILES ['imageUpload'] ['type'] );
			if ($typeOnly == "jpeg")
				$typeOnly = "jpg";
			$imageNameOnly = str_replace ( "." . $typeOnly, "", $_FILES ['imageUpload'] ['name'] );
			$cloudUpload = \Cloudinary\Uploader::upload ( $_FILES ["imageUpload"] ["tmp_name"], array (
					"public_id" => $destination . "/$imageNameOnly" 
			) );
			$imagePath = $cloudUpload ["url"];
			$_SESSION ["imageName"] = $_FILES ["imageUpload"] ["name"];
			$_SESSION ["imagePath"] = $imagePath;
			// show function for user to select
			if (isset ( $_SESSION ["imageName"] ))
				unset ( $_SESSION ["imageName"] );
			if (isset ( $_SESSION ["isWatermarked"] ))
				unset ( $_SESSION ["isWatermarked"] );
			if (isset ( $_SESSION ["isTwoImages"] ))
				unset ( $_SESSION ["isTwoImages"] );
			if (isset ( $_SESSION ["isFramed"] ))
				unset ( $_SESSION ["isFramed"] );
			if (isset ( $_SESSION ["isFunnyEffect"] ))
				unset ( $_SESSION ["isFunnyEffect"] );
			if (isset ( $_SESSION ["backgroundImageName"] ))
				unset ( $_SESSION ["backgroundImageName"] );
			if (isset ( $_SESSION ["backgroundChanged"] ))
				unset ( $_SESSION ["backgroundChanged"] );
			redirect ( base_url () . "/index.php/ImageUpload/ImageUpload/index" );
			
			return;
		} else {
		}
	}
	
	// get Accesstoken
	function getAccessTokenDetails($app_id, $app_secret, $redirect_url, $code) {
		$token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&redirect_uri=" . urlencode ( $redirect_url ) . "&client_secret=" . $app_secret . "&code=" . $code;
		
		$response = file_get_contents ( $token_url );
		$params = null;
		parse_str ( $response, $params );
		return $params;
	}
	
	// get User Details
	function getUserDetails($access_token) {
		$graph_url = "https://graph.facebook.com/me?access_token=" . $access_token;
		$user = json_decode ( file_get_contents ( $graph_url ) );
		if ($user != null && isset ( $user->name ))
			return $user;
		return null;
	}
	//
	
	// get User Friends
	public function getFriendList($session) {
		$result = array ();
		$friendListObj = (new FacebookRequest ( $session, 'GET', "/me/taggable_friends" ))->execute ()->getGraphObject ();
		$backingData = $friendListObj->asArray ();
		$friendList = $backingData ["data"];
		for($i = 0; $i < count ( $friendList ); $i ++) {
			$user = ( array ) $friendList [$i];
			// $newUser["id"] = $user ["id"];
			
			$newUser ["name"] = $user ["name"];
			
			$picture = ( array ) $user ["picture"];
			$picture = ( array ) $picture ["data"];
			$newUser ["description"] = $picture ["url"];
			
			$newUser ["id"] = $user ["id"];
			$newUser ["group"] = 1;
			$result [] = $newUser;
		}
		$result = json_encode ( $result );
		return $result;
		// http://www.script-tutorials.com/facebook-api-get-friends-list/comment-page-2/#comments
	}
	//
	
	// get Friend List
	public function getFriendLists($session){
		$result = array();
		$friendListObj = (new FacebookRequest ( $session, 'GET', "/me/friendlists" ))->execute ()->getGraphObject ();
		$backingData = $friendListObj->asArray ();
		$friendLists = $backingData ["data"];
		for($i = 0; $i < count ( $friendLists ); $i ++) {
			$list = ( array ) $friendLists [$i];
			// $newUser["id"] = $user ["id"];
				
			$newList ["name"] = $list ["name"];
				
				
			$newList ["id"] = $list ["id"];
			$newList ["group"] = 4;
			$result [] = $newList;
		}
		$result = json_encode ( $result );
		return $result;
	}
	
	// Get Granted permission
	public function getGrantedPermission($session) {
		$request = new FacebookRequest ( $session, 'GET', '/me/permissions/publish_actions' );
		$response = $request->execute ();
		$graphObject = $response->getGraphObject ();
		$graphObjectArray = $graphObject->asArray ();
		$object = ( array ) $graphObjectArray [0];
		$status = $object ["status"];
		return $status;
	}
	
	//
	/*
	 * get value of privacy granted (only me, public or friends)
	 */
	public function getPrivacyValue($session) {
		$testResponse = (new FacebookRequest ( $session, 'POST', '/me/feed', array (
				'message' => "Test" 
		) ))->execute ()->getGraphObject ();
		$postId = $testResponse->getProperty ( "id" );
		$testResponse = (new FacebookRequest ( $session, 'GET', "/$postId" ))->execute ()->getGraphObject ();
		$testResponseArray = $testResponse->asArray ();
		$privacy = ( array ) $testResponseArray ["privacy"]; 
		// delete the posted one
		$deleteRequest = new FacebookRequest ( $session, 'DELETE', "/$postId" );
		$response = $deleteRequest->execute ();
		$graphObject = $response->getGraphObject ();
		$deleteResponse = $graphObject->asArray (); 
		
		
// 		var_dump ( $deleteResponse ["success"] );
		if ($deleteResponse ["success"]) {
		} else {
			echo "Cannot delete status";
		}
		return $privacy ["value"];
	}
}

$GLOBALS ["webId"] = 0;
